package com.ruoyi.client.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.bookbus.domain.BookUser;
import com.ruoyi.client.mapper.UserMapper;
import com.ruoyi.client.pojo.form.UserLoginForm;
import com.ruoyi.client.pojo.form.UserRegisterForm;
import com.ruoyi.client.pojo.form.UserUpdateForm;
import com.ruoyi.client.pojo.form.UserUpdatePwdForm;
import com.ruoyi.client.pojo.vo.UserLoginVo;
import com.ruoyi.client.pojo.vo.UserRegisterVo;
import com.ruoyi.client.pojo.vo.UserVo;
import com.ruoyi.client.service.UserService;
import com.ruoyi.common.exception.ServiceException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service("ClientUserServiceImpl")
public class UserServiceImpl implements UserService {

    @Resource(name = "ClientUserMapper")
    private UserMapper userMapper;

    // 用户登录
    @Override
    public UserLoginVo login(UserLoginForm form) {
        BookUser user = userMapper.selectByName(form.getUsername());
        if (user == null) {
            throw new ServiceException("用户名不存在");
        }
        String password = form.getPassword();
        if (password != null && password.equals(user.getPassword())) {
            UserLoginVo userLoginVo = toUserLoginVo(user);
            // 注意：登录token在Controller中设置，Service层只返回用户信息
            return userLoginVo;
        }

        throw new ServiceException("密码错误");
    }

    // 用户注册
    @Override
    public UserRegisterVo register(UserRegisterForm form) {
        BookUser user = userMapper.selectByName(form.getUsername());
        if (user != null) {
            throw new ServiceException("用户名已存在");
        }
        user = new BookUser();
        user.setUsername(form.getUsername());
        user.setPassword(form.getPassword());
        user.setTel(form.getTel());
        if (StringUtils.isNotBlank(form.getAvatar())) {
            user.setAvatar(form.getAvatar());
        }
        user.setRole(0); // 默认普通用户
        user.setCredit(100L); // 默认信用分

        // 调用数据层,注册用户数据
        int result = userMapper.register(user);
        if (result > 0) {
            UserRegisterVo userRegisterVo = toUserRegisterVo(user);
            return userRegisterVo;
        }
        throw new ServiceException("用户注册失败");
    }

    // 查询我的详情
    @Override
    public UserVo getMyDetail() {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        // 1. 按Long读取登录ID
        Long userId = StpUtil.getLoginIdAsLong();
        // 2. 根据用户ID查询用户详情
        BookUser user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        return toUserVo(user);
    }

    // 更改用户信息
    @Override
    public boolean update(UserUpdateForm form) {
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long currentUserId = StpUtil.getLoginIdAsLong();
        
        // 1. 校验id（确保不为null）
        if (form.getId() == null) {
            throw new ServiceException("用户ID不能为空");
        }
        // 验证只能修改自己的信息
        if (!form.getId().equals(currentUserId)) {
            throw new ServiceException("无权修改其他用户信息");
        }
        // 2. 查询用户原有信息（必须存在，否则无法更新）
        BookUser oldUser = userMapper.selectById(form.getId());
        if (oldUser == null) {
            throw new ServiceException("用户不存在");
        }
        // 3. 合并新老数据：仅覆盖非空的新字段
        BookUser userForUpdate = new BookUser();
        userForUpdate.setId(oldUser.getId());
        if (StringUtils.isNotBlank(form.getUsername())) {
            userForUpdate.setUsername(form.getUsername());
        }
        if (StringUtils.isNotBlank(form.getName())) {
            userForUpdate.setName(form.getName());
        }
        if (StringUtils.isNotBlank(form.getPassword())) {
            userForUpdate.setPassword(form.getPassword());
        }
        if (StringUtils.isNotBlank(form.getTel())) {
            userForUpdate.setTel(form.getTel());
        }
        if (StringUtils.isNotBlank(form.getAvatar())) {
            userForUpdate.setAvatar(form.getAvatar());
        }
        // 4. 执行更新
        return userMapper.update(userForUpdate) > 0;
    }

    // 更改用户密码
    @Override
    public boolean updatePwd(UserUpdatePwdForm form) {
        // 用户登录验证,未登录会抛出例外NotLoginException
        if (!StpUtil.isLogin()) {
            throw new ServiceException("用户未登录");
        }
        Long currentUserId = StpUtil.getLoginIdAsLong();

        // 查询用户（根据用户ID获取用户信息）
        BookUser user = userMapper.selectById(currentUserId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }

        // 验证原密码
        String passwordOld = form.getPasswordOld();
        if (!StringUtils.equals(user.getPassword(), passwordOld)) {
            throw new ServiceException("原密码错误");
        }

        // 新密码
        String passwordNew = form.getPasswordNew();
        if (StringUtils.isBlank(passwordNew)) {
            throw new ServiceException("新密码不能为空");
        }

        // 更新密码：必须设置id作为WHERE条件
        BookUser userForUpdate = new BookUser();
        userForUpdate.setId(user.getId());
        userForUpdate.setPassword(passwordNew);

        return userMapper.update(userForUpdate) > 0;
    }

    private UserLoginVo toUserLoginVo(BookUser user) {
        UserLoginVo vo = new UserLoginVo();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setName(user.getName());
        vo.setTel(user.getTel());
        vo.setAvatar(user.getAvatar());
        vo.setRole(user.getRole());
        vo.setCredit(user.getCredit());
        return vo;
    }

    private UserRegisterVo toUserRegisterVo(BookUser user) {
        UserRegisterVo vo = new UserRegisterVo();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setTel(user.getTel());
        vo.setAvatar(user.getAvatar());
        return vo;
    }

    private UserVo toUserVo(BookUser user) {
        UserVo vo = new UserVo();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setName(user.getName());
        vo.setTel(user.getTel());
        vo.setAvatar(user.getAvatar());
        vo.setRole(user.getRole());
        vo.setCredit(user.getCredit());
        return vo;
    }
}